package concurrent;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author jack.wu
 * @since 2019/12/26 17:25
 */
public class CountDownLatchDemo {

    public static class T extends Thread{

        private int runCostSeconds;

        private CountDownLatch commanderCd;

        private CountDownLatch countDown;

        public T(String name, int runCostSeconds, CountDownLatch commanderCd, CountDownLatch countDown) {
            super(name);
            this.runCostSeconds = runCostSeconds;
            this.commanderCd = commanderCd;
            this.countDown = countDown;
        }

        @Override
        public void run() {
            try {
                // 等待指令员开枪
                commanderCd.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(System.currentTimeMillis()+"-"+Thread.currentThread().getName()+"-开始跑");
            try {
                // 模拟跑步耗时
                TimeUnit.SECONDS.sleep(this.runCostSeconds);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                countDown.countDown();
            }
            System.out.println(System.currentTimeMillis()+"-"+Thread.currentThread().getName()+"跑步结束");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch commanderCd = new CountDownLatch(1);
        CountDownLatch countDown = new CountDownLatch(3);

        T t1 = new T("小马",2,commanderCd,countDown);
        T t2 = new T("小新",3,commanderCd,countDown);
        T t3 = new T("小源",5,commanderCd,countDown);
        t1.start();
        t2.start();
        t3.start();

        // 模拟指令员倒计时
        TimeUnit.SECONDS.sleep(3);
        System.out.println("指令员开枪了。。。");
        commanderCd.countDown();

        countDown.await();
        System.out.println("所有人跑完。。");

    }
}
